package com.sky.wsp.rabbitmq.controller;

import com.sky.wsp.rabbitmq.po.EventTypeEnum;
import com.sky.wsp.rabbitmq.po.MqMessage;
import com.sky.wsp.rabbitmq.po.MessageTypeEnum;
import com.sky.wsp.rabbitmq.po.OrgPo;
import com.sky.wsp.rabbitmq.producer.MqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 部门（组织机构）事件消息
 */
@RestController
@RequestMapping("/org")
public class OrgMqController {

    @Autowired
    MqProducer mqProducer;

    @GetMapping("demo")
    public String demo() {
        return "demo";
    }

    @GetMapping(value = "/fanout")
    public String fanout(String name, EventTypeEnum event) {
        OrgPo orgPo = getOrgPo(name);
        MqMessage<OrgPo> msg = getMsg(orgPo, event);
        System.out.println("==> org fanout name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendFanout(msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/direct")
    public String direct(String name, EventTypeEnum event) {
        OrgPo orgPo = getOrgPo(name);
        MqMessage<OrgPo> msg = getMsg(orgPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> org direct routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.senddirectMail(routingKey, msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/topic")
    public String topic(String name, EventTypeEnum event) {
        OrgPo orgPo = getOrgPo(name);
        MqMessage<OrgPo> msg = getMsg(orgPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> org topic routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendtopicMail(routingKey, msg);
        return "ok: " + name;
    }

    private OrgPo getOrgPo(String name) {
        OrgPo orgPo = new OrgPo();
        orgPo.setId("orgId");
        orgPo.setTenantId("tenantId");
        orgPo.setParentId("parentId");
        orgPo.setOrgName(name);
        return orgPo;
    }

    private MqMessage<OrgPo> getMsg(OrgPo orgPo, EventTypeEnum event) {
        return new MqMessage<>()
                .setMessageType(MessageTypeEnum.ORG)
                .setEventType(event)
                .setData(orgPo);
    }

    private String getRoutingKey(EventTypeEnum event){
        return MessageTypeEnum.ORG.name() + "." + event.name();
    }
}
